import requests
from bs4 import BeautifulSoup
import random
import datetime
import time
import json
from pymongo import MongoClient

client = MongoClient('mongodb://127.0.0.1:27017/')  # 本地
db = client['match']
collection = db['hupuidtonbaid']

user_agent = [
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0',
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
    "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
    "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
    "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
    "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
    "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
    "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
    "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)"
]  # 伪装表头，防止反爬


def get_nba_gamelist(year, month):
    url_nba = "http://stat-nba.com/gameList_simple-" + year + "-" + month + ".html"  # nba网的组合地址
    headers = {'User-Agent': random.choice(user_agent)}  # 随机选择一个机型反爬
    html = requests.get(url_nba, headers=headers, timeout=30)
    html.raise_for_status()
    html.encoding = 'utf-8'  # 爬取对应网页
    bs = BeautifulSoup(html.text, 'html.parser')
    jsontext = {'value': []}  # 引入json
    for block in bs.find_all('div', class_='cheight'):
        for date in block.find_all('font', class_='cheightdate'):  # 拿到表格里对应日期
            today = date.get_text().replace(" ", "")
            list_hupu = get_hupu_gamelist(today)  # 通过日期去HUPU查找
            for address in block.find_all('a'):
                for index, l_hupu in enumerate(list_hupu):  # 循环并寻找下标
                    if l_hupu in address.get_text().replace(" ", ""):
                        match = {'Date': today, 'Match': address.get_text().replace(" ", ""), 'HUPU': list_hupu[index + 1],
                             'NBA': address['href'][address['href'].rfind('game'):][5:10], 'Video_address': ''}

                        match = json.dumps(match, ensure_ascii=False, indent=4, separators=(',', ': '))  # 整合进json
                        collection.insert_one(match)
                        """
                        jsontext['value'].append(
                            {'Date': today, 'Match': address.get_text().replace(" ", ""), 'HUPU': list_hupu[index + 1],
                             'NBA': address['href'][address['href'].rfind('game'):][5:10], 'Video_address': ''})
                        # 写入单个json
    jsondata = json.dumps(jsontext, ensure_ascii=False, indent=4, separators=(',', ': '))  # 整合进json
    with open('Compared' + year + month + '.json', 'w', encoding="utf-8") as jsonf:  # 写入文件
        jsonf.write(jsondata)
        jsonf.close()
        """
    return 'Compared' + year + month + '.json'


def get_hupu_gamelist(today):
    date = date_change(today)
    url_hupu = "https://nba.hupu.com/games/" + date  # 整理地址
    headers = {'User-Agent': random.choice(user_agent)}  # 随机选择一个机型反爬
    html = requests.get(url_hupu, headers=headers, timeout=30)
    html.raise_for_status()
    html.encoding = 'utf-8'  # 爬取对应网页
    bs = BeautifulSoup(html.text, 'html.parser')
    list = []  # 返回一个二维列表
    for block in bs.find_all('div', class_='border_a'):
        name = block.find_all('div', class_='txt')
        list.append(name[1].get_text().replace("\n", ""))  # 对HUPU网站的比赛爬取之后写入列表
        for address in block.find_all('a', class_='d'):
            list.append(address['href'][address['href'].rfind('boxscore'):][9:])
    print('正在爬取HUPU网站' + date)  # 延时很重要，防止别网站拉黑
    time.sleep(1)  # 延时很重要，防止别网站拉黑
    return list

def date_change(today):
    date = datetime.datetime.strptime(today, "%Y-%m-%d")
    date = date + datetime.timedelta(days=1)
    date = date.strftime('%Y-%m-%d')  # 对 HUPU 的时间整体增加一天以匹配美国时间
    return date

if __name__ == '__main__':
    year = input("请输入要查找的年份，如2020：")
    month = input("请输入要对应的月份，如01：")
    print("数据对照爬取已完成，请检查文件" + get_nba_gamelist(year, month))